# ../addons/manilib/core/clients/readclients.py

'''
$Rev: 6 $
$Author: pitkley $
$Date: 2009-11-01 11:19:13 +0000 (Sun, 01 Nov 2009) $
'''

# ==============================================================================
# >> IMPORTS
# ==============================================================================
# Python Imports
from os import path

# EventScripts Imports
import es

# Manilib Imports
from core import get_game_dir
from core.clients.client.shortcuts import addClient
# ==============================================================================
# >> GLOBALS
# ==============================================================================
dict_mClients   = {}
dict_mGroups    = {"admin":[], "immunity":[]}
dict_mLevels    = {"admin":[], "immunity":[]}
clientsPath     = get_game_dir("cfg/mani_admin_plugin/clients.txt")

# ==============================================================================
# >> CLASSES
# ==============================================================================
class ReadClients(object):
    def __init__(self):
        if not path.isfile(clientsPath):
            raise ManilibError("Couldn't load clients.txt: no such file!")

    def read_clients(self):
        # Open clients.txt, read lines, close file
        file_mClients   = open(clientsPath, 'r')
        lines_mClients  = file_mClients.readlines()
        file_mClients.close()

        # Tuple for correct (not comment) lines
        list_mCorrectLines = []

        # Parse file
        for line in lines_mClients:
            # Remove indention but add a space between quotesigns (")
            line = line.replace("\t", "").replace('""', '" "')
            # Sort lines wrong lines out
            if not line.startswith("//") and not \
                line.startswith('"clients.txt"') and not \
                line.startswith('"version"') and not line == "\n" and not \
                line.startswith("{") and not line.startswith("}") and not \
                line.startswith('"players"'):
                    list_mCorrectLines.append(line.replace("\n", ""))

        # Parse correctlines
        for line in list_mCorrectLines:
            # Get clients
            if line.startswith('"name" "'):
                # Define line indexes
                startindex  = list_mCorrectLines.index(line)
                homeindex   = startindex - 1
                flagsstart  = homeindex + 3
                # Create names and steamids tuples
                names       = []
                steamids    = []
                # Parse the uniqueid
                uniqueid = list_mCorrectLines[homeindex].replace('"', '')

                # Loop through names
                while list_mCorrectLines[startindex].startswith('"name" "'):
                    # Append parsed name
                    names.append(list_mCorrectLines[startindex]
                        .replace('"name" "', '').replace('"', ''))
                    startindex += 1
                # Loop through steamids
                while list_mCorrectLines[startindex].startswith('"steam" "'):
                    # Append parsed steamid
                    steamids.append(list_mCorrectLines[startindex]
                        .replace('"steam" "', '').replace('"', ''))
                    startindex += 1

                # Add the new client with the fetched data
                mClient = addClient(uniqueid, names[0], steamids[0])
                # Initialize client admin and immunity flags
                mClient.adminflags      = []
                mClient.immunityflags   = []

                # Get client admin and immunity flags
                if list_mCorrectLines[flagsstart] == '"flags"':
                    flagsindex = flagsstart + 1

                    while list_mCorrectLines[flagsindex] \
                        .startswith('"Immunity" "'):
                            for flag in list_mCorrectLines[flagsindex] \
                                .replace('"Immunity" "', '') \
                                .replace('"', '').split():
                                    mClient.immunityflags.append(flag)
                            flagsindex += 1
                    while list_mCorrectLines[flagsindex] \
                        .startswith('"Admin" "'):
                            for flag in list_mCorrectLines[flagsindex] \
                                .replace('"Admin" "', '') \
                                .replace('"', '').split():
                                    mClient.adminflags.append(flag)
                            flagsindex += 1
                    start = flagsindex
                else:
                    start = flagsstart

                # Initialize client admin and immunity groups
                mClient.admingroups     = []
                mClient.immunitygroups  = []
                # Get client admin and immunity groups
                if list_mCorrectLines[start] == '"groups"':
                    groupindex = start + 1
                    while list_mCorrectLines[groupindex] \
                        .startswith('"Admin" "'):
                            mClient.admingroups.append(
                                list_mCorrectLines[groupindex] \
                                    .replace('"Admin" "', '').replace('"', ''))
                            groupindex += 1
                    while list_mCorrectLines[groupindex] \
                        .startswith('"Immunity" "'):
                            mClient.immunitygroups.append(
                                list_mCorrectLines[groupindex] \
                                    .replace('"Immunity" "', '') \
                                    .replace('"', ''))
                            groupindex += 1
                    start = gropindex

                # Initialize client admin and immunity levels
                mClient.adminlevels     = []
                mClient.immunitylevels  = []
                # Get client admin and immunity levels
                if list_mCorrectLines[start] == '"levels"':
                    levelindex = start + 1
                    while list_mCorrectLines[levelindex] \
                        .startswith('"Admin" "'):
                            mClient.adminlevels.append(
                                list_mCorrectLines[levelindex] \
                                    .replace('"Admin" "', '').replace('"', ''))
                            levelindex += 1
                    while list_mCorrectLines[levelindex] \
                        .startswith('"Immunity" "'):
                            mClient.immunitylevels.append(
                                list_mCorrectLines[levelindex] \
                                    .replace('"Immunity" "', '') \
                                    .replace('"', ''))
                            levelindex += 1
                    start = levelindex
            # Get groups
            